import { ElMessageBox } from 'element-plus'
import { binMsg } from '@/global/api.js'
import { titleCase } from '@/utils/utils.js'
import { searchCourseByType } from '@/services/course.js'
import {
  saveLesson,
  searchLessonByKey,
  removeLesson,
  searchStudentByTidAndStuName
} from '@/services/selectLesson.js'
import { searchHistories, clearHistories } from '@/services/selectHistories.js'
import { formatNowTime } from '@/utils/formatDate.js'

// 学生选课模块
const selectCourseModule = {
  namespaced: true,
  state() {
    return {
      // 主修
      majorCourseList: [],
      majorCourseCount: 0,
      // 选修
      electiveCourseList: [],
      electiveCourseCount: 0,
      // 选课情况列表
      caseList: [],
      caseCount: 0,
      // 选退课历史
      historiesList: [],
    }
  },

  mutations: {
    changeMajorCourseList(state, list) {
      state.majorCourseList = list
    },
    changeMajorCourseCount(state, count) {
      state.majorCourseCount = count
    },
    changeElectiveCourseList(state, list) {
      state.electiveCourseList = list
    },
    changeElectiveCourseCount(state, count) {
      state.electiveCourseCount = count
    },
    changeCaseList(state, list) {
      state.caseList = list
    },
    changeCaseCount(state, count) {
      state.caseCount = count
    },
    changeHistoriesList(state, list) {
      state.historiesList = list
    },
    // 清空数组数据
    clearState(state) {
      state.majorCourseList = []
      state.electiveCourseList = []
      state.caseList = []
      state.historiesList = []
    }
  },

  actions: {
    // 查询
    async searchAction({ commit }, payload) {
      const { data: res } = await searchCourseByType(payload)
      commit(`change${titleCase(payload.pageName)}CourseList`, res.data.list)
      commit(`change${titleCase(payload.pageName)}CourseCount`, res.data.total)
    },

    // 选课操作
    async saveAction({ commit, state, dispatch, rootState }, payload) {
      try {
        await ElMessageBox.confirm('确认选择该课程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true
        })
        // console.log('saveAction:', payload);
        const pageName = payload.pageName
        delete payload.pageName
        const { data: res } = await saveLesson(payload)
        if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
        // console.log('res:',res)
        const saveData = res.data.data
        const newCourseList = state[`${pageName}CourseList`].map((item) => {
          if (item.id === saveData.cid) {
            return { ...item, remaining: item.remaining - 1 }
          } else {
            return item
          }
        })
        commit(`change${titleCase(pageName)}CourseList`, newCourseList)
        // 选课成功过后，重新查询已选课程数据
        dispatch('searchCaseAction', { label: 'cname', value: '', page_num: 1, page_size: 10 })
        binMsg('success', res.meta.msg)
        dispatch('searchHistoriesAction', { stu_num: rootState.userModule.userInfo.stu_num })
      } catch (e) {
        binMsg('info', '已取消')
      }
    },

    // 我的选课：根据课程名称，教师名称进行模糊查询
    async searchCaseAction({ commit, rootState }, payload) {
      // console.log('searchCaseAction', payload)
      payload.stu_num = rootState.userModule.userInfo.stu_num
      const { data: res } = await searchLessonByKey(payload)
      commit(`changeCaseList`, res.data.list)
      commit(`changeCaseCount`, res.data.total)
    },

    // 退课操作
    async removeAction({ commit, state, dispatch, rootState }, payload) {
      try {
        await ElMessageBox.confirm('确认进行退课操作吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true
        })
        const stu_num = rootState.userModule.userInfo.stu_num
        payload.stu_num = stu_num
        const { data: res } = await removeLesson(payload)
        if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
        const lessons = state.caseList.filter((item) => item.id !== payload.id)
        commit('changeCaseList', lessons)
        commit('changeCaseCount', state.caseCount - 1)
        dispatch('searchAction', {
          pageName: payload.type === 1 ? 'major' : 'elective',
          label: 'course_name',
          value: '',
          page_num: 1,
          page_size: 10
        })
        dispatch('searchHistoriesAction', { stu_num })
        binMsg('success', res.meta.msg)
      } catch (e) {
        binMsg('info', '已取消')
      }
    },

    //===========选课退课历史==========
    // 查询选退课记录
    async searchHistoriesAction({ commit }, payload) {
      const { data: res } = await searchHistories(payload.stu_num)
      if (res.meta.status !== 200) return
      commit('changeHistoriesList', res.data.data)
    },
    // 清空选退课历史记录
    async clearHistoriesAction({ commit }, payload) {
      const { data: res } = await clearHistories(payload.stu_num)
      console.log(res)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      commit('changeHistoriesList', [])
      binMsg('success', res.meta.msg)
    }
  },

  getters: {
    // 主修、选修课程列表
    pageList(state) {
      return (name) => {
        // 处理上课时间，改成这种形式：【星期一 8:30~10:05】 -> (1).11
        // 原因是：连级选择器只有当最后一级的值相同时，才会将数据回显，再修改课程时使用
        return state[`${name}CourseList`].map((item) => {
          return {
            ...item,
            time_1: `(${String(item.time_1).split('')[0]}).${item.time_1}`,
            time_2: `(${String(item.time_2).split('')[0]}).${item.time_2}`
          }
        })
      }
    },
    // 主修、选修课程列表数量
    pageCount(state) {
      return (name) => {
        return state[`${name}CourseCount`]
      }
    },
    historiesList(state) {
      return state.historiesList.map((item) => {
        return { ...item, selectAt: formatNowTime(Number(item.selectAt)) }
      })
    }
  }
}

export default selectCourseModule
